<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;

class Localization
{
  public function handle($request, Closure $next)
  {
    $currLocale = null;

    if ($request->has('locale')) {
      $currLocale = $request->locale;
      App::setLocale($currLocale);
      Log::debug('Locale settato da $request->locale');
    } else {
      if (App::getLocale()) {
        $currLocale = App::getLocale();
        Log::debug('Locale settato da App:getLocale()');
      }
    }
    $fallbackLocale = config('app.fallback_locale');
    $availableLocales = config('coreapi.supported_locales');
    $newLocale = ($request->hasHeader('Content-Language')) ? $request->header('Content-Language') : $currLocale;
    if (!in_array($newLocale, $availableLocales)) {
      $newLocale = $fallbackLocale;
    }
    App::setLocale($newLocale);

    return $next($request);
  }
}
